<?php

/**
 * Set Error Reporting 
 */
function set_error_reporting($s_Log_Path) {
    if (DEVELOPMENT_ENVIRONMENT == true) {
        error_reporting(E_ALL);
        ini_set('display_errors', 'on');
    } else {
        error_reporting(E_ALL);
        ini_set('display_errors', 'off');
        ini_set('log_errors', 'on');
        ini_set('error_log', $s_Log_Path . 'error.log');
    }
}

/**
 * Check if register_globals is on, delete all variables exept the ones in the array.
 *
 */
function unregister_globals() {
    if (ini_get('register_globals')) {
        $a_args = array('_SESSION', '_POST', '_GET', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES');
        foreach ($a_args as $v_value) {
            if (isset($GLOBALS[$v_value])) {
                foreach ($GLOBALS[$v_value] as $v_key => $v_var) {
                    if (isset($GLOBALS[$v_key]) && $v_var === $GLOBALS[$v_key]) {
                        unset($GLOBALS[$v_key]);
                    }
                }
            }
        }
    }
}

/**
 * Remove magic quotes from request data.
 *
 */
function remove_strip_slashes(&$a_args) {
    if (is_array($a_args) || is_object($a_args)) {
        foreach ($a_args as $v_key => $v_val) {
            remove_strip_slashes($a_args[$v_key]);
        }
    } elseif (is_string($a_args)) {
        $a_args = stripslashes($a_args);
        $a_args = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $a_args);            
        if (strpos($a_args, "\r") !== false) {
            $a_args = str_replace(array("\r\n", "\r"), "\n", $a_args);                
        }        
    }
}

/**
 * Get Cache File.
 *
 */
function access_cachefile($s_Cache_Path, $v_cachefile, $aOption = array()) {

    $aOption = array_merge(array (
        'db_conn'             => null,
        'loai_chuyencan' => array ( ),
        'generate'            => false,
        ), $aOption);

    $db_conn    = $aOption['db_conn'];
    $f_generate = $aOption['generate'];

    if (!$f_generate) {
        $v_TmpCachefile = $s_Cache_Path . $v_cachefile;
        if (file_exists($v_TmpCachefile)) {
            $o_handle = fopen($v_TmpCachefile, 'rb');
            $a_vars   = fread($o_handle, filesize($v_TmpCachefile));
            fclose($o_handle);
            return unserialize($a_vars);
        }
    }

    if ($db_conn instanceof mysqli) {
        $aTemp = array ( );
        switch ($v_cachefile) {
            case 'passport_pages':
                $db_query  = "select pageid, moduleid from passport_module_page";
                $db_result = db_query($db_conn, $db_query);

                while ($d_row = db_fetch($db_result)) {
                    $aTemp[$d_row->pageid] = $d_row->moduleid;
                }
                break;
                
            case 'passport_actions':
                $db_query  = "select actionid, actionname from passport_action order by actionname";
                $db_result = db_query($db_conn, $db_query);

                while ($d_row = db_fetch($db_result)) {
                    $aTemp[$d_row->actionid] = $d_row->actionname;
                }
                break;
                
            case 'attendance_card':
                $a_Loai_ChuyenCan = $aOption['loai_chuyencan'];
                $db_query  = "
                    select  option_id, option_type, option_status, option_key, option_data
                    from    system_option
                    where   option_type in ('".implode("', '", $a_Loai_ChuyenCan)."')
                    order by option_type, option_key";
                $db_result = db_query($db_conn, $db_query);

                while ($d_row = db_fetch($db_result)) {
                    $d_row->option_data  = json_decode($d_row->option_data);
                    $d_row->option_score = $d_row->option_data->option_score;
                    $d_row->option_name  = $d_row->option_data->option_name;
                    unset($d_row->option_data);

                    $aTemp[$d_row->option_type][$d_row->option_key] = (array)$d_row;
                }
                break;
                
            case 'team':
                $db_query  = "
                    select  option_id, option_type, option_status, option_key, option_data
                    from    system_option
                    where   option_type = 'NGANH'
                    order by option_id";
                $db_result = db_query($db_conn, $db_query);

                while ($d_row = db_fetch($db_result)) {
                    $aTemp[$d_row->option_key] = $d_row->option_data;
                }
                break;
                
            case 'level':
                $db_query  = "
                    select  option_id, option_type, option_status, option_key, option_data
                    from    system_option
                    where   option_type = 'CAP'
                    order by option_id";
                $db_result = db_query($db_conn, $db_query);

                while ($d_row = db_fetch($db_result)) {
                    $aTemp[$d_row->option_key] = $d_row->option_data;
                }
                break;
                
            case 'crew':
                $db_query  = "
                    select  option_id, option_type, option_status, option_key, option_data
                    from    system_option
                    where   option_type = 'DOI'
                    order by option_id";
                $db_result = db_query($db_conn, $db_query);

                while ($d_row = db_fetch($db_result)) {
                    $aTemp[$d_row->option_key] = $d_row->option_data;
                }
                break;
                
            case 'usercrew':
                $db_query  = "
                    select  option_id, option_type, option_status, option_key, option_data
                    from    system_option
                    where   option_type = 'PHAN_BAN'
                    order by option_id";
                $db_result = db_query($db_conn, $db_query);

                while ($d_row = db_fetch($db_result)) {
                    $aTemp[$d_row->option_key] = $d_row->option_data;
                }
                break;
                
            case 'usertype':
                $db_query  = "
                    select  option_id, option_type, option_status, option_key, option_data
                    from    system_option
                    where   option_type = 'LOAI_TAI_KHOAN'
                    order by option_id";
                $db_result = db_query($db_conn, $db_query);

                while ($d_row = db_fetch($db_result)) {
                    $aTemp[$d_row->option_key] = $d_row->option_data;
                }
                break;
                
            case 'userrank':
                $db_query  = "
                    select  option_id, option_type, option_status, option_key, option_data
                    from    system_option
                    where   option_type = 'XEP_HANG'
                    order by option_id";
                $db_result = db_query($db_conn, $db_query);

                while ($d_row = db_fetch($db_result)) {
                    $aTemp[$d_row->option_key] = $d_row->option_data;
                }
                break;
                
            case 'relationship':
                $db_query  = "
                    select  option_id, option_type, option_status, option_key, option_data
                    from    system_option
                    where   option_type = 'MOI_QUAN_HE'
                    order by option_id";
                $db_result = db_query($db_conn, $db_query);

                while ($d_row = db_fetch($db_result)) {
                    $aTemp[$d_row->option_key] = $d_row->option_data;
                }
                break;
                
            case 'examtype':
                $db_query  = "
                    select  option_id, option_type, option_status, option_key, option_data
                    from    system_option
                    where   option_type = 'DOT_KIEM_TRA'
                    order by option_id";
                $db_result = db_query($db_conn, $db_query);

                while ($d_row = db_fetch($db_result)) {
                    $aTemp[$d_row->option_key] = $d_row->option_data;
                }
                break;
                
            case 'examtime':
                $db_query  = "
                    select  option_id, option_type, option_status, option_key, option_data
                    from    system_option
                    where   option_type = 'LAN_KIEM_TRA'
                    order by option_id";
                $db_result = db_query($db_conn, $db_query);

                while ($d_row = db_fetch($db_result)) {
                    $aTemp[$d_row->option_key] = $d_row->option_data;
                }
                break;

            default:
                return array ( );
                break;
        }

        set_cachefile($s_Cache_Path, $v_cachefile, $aTemp);
        return access_cachefile($s_Cache_Path, $v_cachefile);
    }

    return array ( );
}

/**
 * Set Cache File.
 *
 */
function set_cachefile($s_Cache_Path, $v_cachefile, $a_vars) {
    $v_cachefile = $s_Cache_Path . $v_cachefile;
    if (file_exists($v_cachefile)) {
        @unlink($v_cachefile);
    }
    $o_handle = fopen($v_cachefile, 'a');
    fwrite($o_handle, serialize($a_vars));
    fclose($o_handle);
}

/**
 * Format Date
 * @param type $v_date
 * @param type $v_do_show_time
 * @param type $v_do_show_plain_text
 * @return type
 */
function namhoa_date($v_date, $v_do_show_time = false, $v_do_show_plain_text = false) {
    
    if(namhoa_checkdate($v_date) == 'N/A') {
        return;
    }
    
    if($v_do_show_plain_text) {
        return $v_date;
    }
    
    $v_strtotime = strtotime($v_date);
    
    $v_time = date('H:i', $v_strtotime);
    
    if(0) {
        
        $v_checkdate = substr($v_date, 0, 10);
    
        if($v_checkdate == date('Y-m-d')) {
            return 'Today ' . $v_time;
        }
        else if($v_checkdate == date('Y-m-d', strtotime('-1 day'))){
            return 'Yesterday' . $v_time;
        }
        else if($v_checkdate == date('Y-m-d', strtotime('-2 day'))){
            return '2 days ago ' . $v_time;
        }
        else if($v_checkdate == date('Y-m-d', strtotime('-3 day'))){
            return '3 days ago ' . $v_time;
        }
        else if($v_checkdate == date('Y-m-d', strtotime('-4 day'))){
            return '4 days ago ' . $v_time;
        }
        else if($v_checkdate == date('Y-m-d', strtotime('-5 day'))){
            return '5 days ago ' . $v_time;
        }
        else if($v_checkdate == date('Y-m-d', strtotime('-6 day'))){
            return '6 days ago ' . $v_time;
        }
        else if($v_checkdate == date('Y-m-d', strtotime('-7 day'))){
            return '7 days ago ' . $v_time;
        }
        else if($v_checkdate == date('Y-m-d', strtotime('-8 day'))){
            return '8 days ago ' . $v_time;
        }
        else if($v_checkdate == date('Y-m-d', strtotime('-9 day'))){
            return '9 days ago ' . $v_time;
        }
        else if($v_checkdate == date('Y-m-d', strtotime('-10 day'))){
            return '10 days ago ' . $v_time;
        }
    }
    
    if ($v_strtotime <= strtotime('1970-01-01')) { return ''; }
    
    $v_date = date('d-m-Y', $v_strtotime);
    
    if($v_do_show_time) {
        return "$v_date $v_time";
    }
    return $v_date;
}

/**
 * Check if $date is not avalable date  return 'N/A' else return $date;
 * @param date $date
 * @return string 
 */
function namhoa_checkdate($date) {
    if (strpos($date, '0000-00-00') === false) {
        return $date;
    }
    return 'N/A';
}

/**
 * Convert to date('Y-m-d')
 * @param date $date
 * @return date
 */
function format_date($date, $date_type = 'Y-m-d') {
    
    switch ($date_type) {
        case 'Y-m-d':
            if (namhoa_strpos($date, '-') == -1) { return '1900-01-01'; }

            $dates = explode('-', $date);
            $count = count($dates);
            if($count != 3){ return '1900-01-01';}

            $year  = intval($dates[0]);
            $month = intval($dates[1]);
            $day   = intval($dates[2]);

            break;
            
        case 'd/m/Y':
            if (namhoa_strpos($date, '/') == -1) { return '1900-01-01'; }

            $dates = explode('/', $date);
            $count = count($dates);
            if($count != 3){ return '1900-01-01';}

            $year  = intval($dates[2]);
            $month = intval($dates[1]);
            $day   = intval($dates[0]);

            break;

        default:
            return '1900-01-01';
            break;
    }

	if (checkdate($month, $day, $year) === false) { return '1900-01-01'; }

	return date('Y-m-d', mktime(0, 0, 0, $month, $day, $year));
}

function local_redirect($v_returnurl, $v_message = '', $v_seconds = 0, $v_alert = false) {
    $title = 'Redirecting...';
    $alert = $v_alert ? "<script type='text/javascript'>alert('$v_message');</script>" : '';

    if (!headers_sent()) {
        echo "<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN' 'http://www.w3.org/TR/html4/strict.dtd'>
              <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
                    <head>
                        <title>$title</title>
                        <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
                        <meta http-equiv='Refresh' content='$v_seconds;url=$v_returnurl'>
                        $alert
                    </head>
                    <body><div>",($v_alert ? '' : filter_html($v_message)),"</div></body>
              </html>";
    } else {
        $v_returnurl = str_replace('&amp;', '&', $v_returnurl);
        echo "$alert<script type='text/javascript'>document.title = '$title';document.location = '$v_returnurl';</script>";
    }

    exit;
}

/**
 * Convert special characters in $text to HTML entities with encode=UTF-8
 * @param string $text
 * @return string 
 */
function check_plain($text) {
    return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}

function filter_html($str, $allowable_tags = '<span><p><a><br><ul><ol><li><b><i><u><em><strong><table><tbody><thead><tfoot><tr><th><td><h1><h2><h3><h4><h5><h6><blockquote><div>') {
    return strip_tags($str, $allowable_tags);
}

function raise_alert($v_message = 'Page not found! Please report broken link to us. Thank you!') {
    $v_message = str_replace("\n", '\n', $v_message);
    
    echo "
        <!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN' 'http://www.w3.org/TR/html4/strict.dtd'>
        <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
              <head>
                  <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
                  <script type='text/javascript' charset='UTF-8' > alert('$v_message');</script>
              </head>
              <body></body>
        </html>";
}

function namhoa_pagelink(&$s_Pagination, &$s_ScriptName, &$s_QueryString, &$i_Page, &$i_Page_Size, &$s_Page_Start, &$d_total = 1, &$v_pagelink = 3, &$a_navigations = array(10, 50, 100)) {

	if($d_total <= $i_Page_Size) { return; }

    $s_Pagination   =  '';
    $v_href         = '<a href="' . $s_ScriptName . '?' . $s_QueryString . '&amp;page=%d" title="%s %d to %d of %d">%s</a>';

	$v_totalpage    = ceil($d_total / $i_Page_Size);
    
	if($i_Page > 1) {
		$v_prevpage     = $i_Page - 1;
		fetch_start_end_total($v_first, $v_last, $v_prevpage, $i_Page_Size, $d_total);
        $s_Pagination   = $s_Pagination . '<li>'. sprintf($v_href, $v_prevpage, 'Prev page - Result', $v_first, $v_last, $d_total, '&laquo;') . '</li>';
	}
    else {
        $i_Page = 1;
    }

    $i = 0;

    while($i++ < $v_totalpage) {
        $v_abs = abs($i - $i_Page);
		if ($v_abs >= $v_pagelink && $v_pagelink != 0) {
			if ($i == 1) {
				fetch_start_end_total($v_first, $v_last, $i, $i_Page_Size, $d_total);
                $s_Pagination  = $s_Pagination . '<li>'. sprintf($v_href, $i, 'First page - Result', $v_first, $v_last, $d_total, $i) . '</li>';
			}
            if($v_abs == $v_pagelink && $i != 1 && $i != $v_totalpage) {
                $s_Pagination  = $s_Pagination . '<li><a>...</a></li>';
            }
			if ($i == $v_totalpage) {
				fetch_start_end_total($v_first, $v_last, $v_totalpage, $i_Page_Size, $d_total);
                $s_Pagination = $s_Pagination . '<li>'. sprintf($v_href, $v_totalpage, 'Last page - Result', $v_first, $v_last, $d_total, $v_totalpage) . '</li>';
			}
			if (in_array($v_abs, $a_navigations) && $i != 1 && $i != $v_totalpage) {
				fetch_start_end_total($v_first, $v_last, $i, $i_Page_Size, $d_total);
                $s_Pagination = $s_Pagination . '<li>'. sprintf($v_href, $i, 'Show results', $v_first, $v_last, $d_total, $i) . '</li>';
			}
		}
		else {
			if ($i == $i_Page) {
				fetch_start_end_total($v_first, $v_last, $i, $i_Page_Size, $d_total);
                $s_Pagination = $s_Pagination . '<li class="active" title="Show results ' . $v_first . ' to ' . $v_last . ' of ' . $d_total . '"><a>'. $i . '</a></li>';
			}
			else {
				fetch_start_end_total($v_first, $v_last, $i, $i_Page_Size, $d_total);
                $s_Pagination = $s_Pagination . '<li>'. sprintf($v_href, $i, 'Show results', $v_first, $v_last, $d_total, $i) . '</li>';
			}
		}
    }

    if($i_Page < $v_totalpage) {
        $v_nextpage     = $i_Page + 1;
        fetch_start_end_total($v_first, $v_last, $v_nextpage, $i_Page_Size, $d_total);
        $s_Pagination   = $s_Pagination . '<li>'. sprintf($v_href, $v_nextpage, 'Next page - Result', $v_first, $v_last, $d_total, '&raquo;') . '</li>';
    }

    $s_Page_Start = ($i_Page - 1) * $i_Page_Size;

    if($s_Page_Start > $d_total) {
        $s_Page_Start = $d_total - $i_Page_Size - 1;
    }

    if($s_Page_Start < 0) {
       $s_Page_Start = 0;
    }

    $s_Pagination   = '<div class="pagination"><ul><li><a>Tổng: ' . $d_total . ' | Trang ' . $i_Page . ' / ' . $v_totalpage . '</a></li>' . $s_Pagination . '</ul></div>';
}

function fetch_start_end_total(&$v_first, &$v_last, &$v_page, &$i_Page_Size, &$d_total) {
	$v_first  = $i_Page_Size * ($v_page - 1);
	$v_last   = $v_first + $i_Page_Size;

	if($v_last > $d_total) {
		$v_last = $d_total;
	}

	$v_first = $v_first + 1;
}

/**
 * Validate date if day <= 31, month <= 12
 * @param date $v_date
 * @return bool; 
 */
function validate_date(&$v_date) {
    $v_date = trim($v_date);
    
    if($v_date == '') {
        return false;
    }
    
    if(!preg_match('/^(?<year>[1-9][0-9]{3})-(?<month>(0?[1-9])|(1[0-2]))-(?<day>(0?[1-9])|([12][0-9])|(3[0-1]))$/', $v_date, $a_match)) {
        return false;
    }
    
    $v_maxday = date('t', mktime(0, 0, 0, $a_match['month'], 1, $a_match['year'])) + 1;
    return intval($a_match['day']) < $v_maxday;
}

function raise_error($message = 'Page not found! Please report broken link to us. Thank you!', $option = array()) {
    $message = str_replace("\n", '\n', $message);
    $message = "<script type='text/javascript' charset='UTF-8'> alert('$message'); </script>\n";
    
    $option = array_merge(array(
            'close-popup' => false,
        ),
        $option
    );
    
    if ($option['close-popup']) { $message .= "<script type='text/javascript' charset='UTF-8'> window.close(); </script>\n"       ; }
    else                        { $message .= "<script type='text/javascript' charset='UTF-8'> window.history.go(-1); </script>\n"; }
    
    echo "
        <!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN' 'http://www.w3.org/TR/html4/strict.dtd'>
        <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
              <head>
                  <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
                  $message
              </head>
              <body></body>
        </html>";
    
    exit;
}

function deserialize_query_string($s_QueryString) {
    $a_result = array();
    
    if($a_groups = preg_split('/&/', $s_QueryString, -1, PREG_SPLIT_NO_EMPTY)) {
        foreach($a_groups as $v_group) {
            $a_pair = explode('=', $v_group, 2);
            $v_key  = trim($a_pair[0]);
            
            if($v_key !== '') {
                $a_result[$v_key] = isset($a_pair[1]) ? $a_pair[1] : '';
            }
        }
    }
    
    return $a_result;
}

function show_data_list(&$a_data) {    
    if(empty($a_data)) {
        return;
    }
    
    $j = 0;
    
    $v_list = '';
    
    foreach ($a_data as $v_key => $v_value) {
        if ($j > 5) {
            break;
        }
        $v_list = $v_list . '<div>' . $v_value . '</div>';

        $j++;

        unset($a_data[$v_key]);
    }
    if (!empty($a_data)) {
        foreach ($a_data as $v_key => $v_value) {
            $v_list = $v_list . '<div class="display-none data_hidden">' . $v_value . '</div>';
        }
        $v_list = $v_list . '<div><a href="javascript://" onclick="namhoa.expander(this);" class="expander more"><b>more</b> <small>▼</small></a></div>';
    }
    return $v_list;
}

/**
 * Get Week Days
 * @param string $startDate
 * @param string $endDate
 * @param int $weekdayNumber
 * @return dateArr 
 */
function getDateForSpecificDayBetweenDates($startDate, $endDate, $weekdayNumber = 0) {
    $startDate = strtotime($startDate);
    $endDate   = strtotime($endDate);

    $dateArr = array ( );

    do {
        if (date("w", $startDate) != $weekdayNumber) {
            $startDate += (24 * 3600); // add 1 day
        }
    } while (date("w", $startDate) != $weekdayNumber);


    while ($startDate <= $endDate) {
        $dateArr[] = date('Y-m-d', $startDate);
        $startDate += (7 * 24 * 3600); // add 7 days
    }

    return($dateArr);
}

/**
 * Get Minus Score
 * @param string $attendance_key
 * @return minus 
 */
function get_minus_score($attendance_key) {
    
    $_tmp_minus = 0;
    
    switch ($attendance_key) {
        case 'T':
            $_tmp_minus = 0.3;
            break;
        case 'H':
        case 'P':
            $_tmp_minus = 0.2;
            break;
        case 'K':
            $_tmp_minus = 0.5;
            break;
        default:
            break;
    }
    
    return $_tmp_minus;
}

/**
 * Get Rank base on Score
 * @param int $score
 * @param string $type
 * @return o_rank 
 */
function get_rank_type($score, $type) {
    
    $o_rank = new stdClass();
    $o_rank->key = $o_rank->value ='';
    
    switch ($type) {
        
        case 'HOC_LUC':
                 if ($score >=   8) { $o_rank->key = 'GIOI'      ; $o_rank->value = 'Giỏi'       ; }   
            else if ($score >= 6.5) { $o_rank->key = 'KHA'       ; $o_rank->value = 'Khá'        ; }
            else if ($score >=   5) { $o_rank->key = 'TRUNG_BINH'; $o_rank->value = 'Trung Bình' ; }
            else                    { $o_rank->key = 'YEU'       ; $o_rank->value = 'Yếu'        ; }
            break;

        case 'CHUYEN_CAN':
            
                 if ($score >=   8) { $o_rank->key = 'TOT'       ; $o_rank->value = 'Tốt'        ; }
            else if ($score >= 6.5) { $o_rank->key = 'KHA'       ; $o_rank->value = 'Khá'        ; }
            else if ($score >=   5) { $o_rank->key = 'TRUNG_BINH'; $o_rank->value = 'Trung Bình' ; }
            else                    { $o_rank->key = 'YEU'       ; $o_rank->value = 'Yếu'        ; }
            break;

        default:
            break;
    }
    return $o_rank;
}

/**
 * User Information
 * @param array $a_users
 * @param connection $db_conn
 * @return array 
 */
function get_user_info($a_users, $db_conn) {
    
    if ( !is_array($a_users) || empty($a_users)) { return array(); }
    
    $o_user           = new stdClass();
    $o_user->userid   = '';
    $o_user->usertype = '';
    $o_user->saint    = '';
    $o_user->username = '';

    $db_query = "
        select  ". implode(", ", array_keys((array)$o_user) ) ."
        from    user
        where   userid in ('" . implode("', '", $a_users) . "')";
    
    $db_result = db_query($db_conn, $db_query);

    $a_Tmp_Users = array();
    
    foreach ($a_users as $key) {
        $a_Tmp_Users[$key] = clone $o_user;
    }

    while ($d_row = db_fetch($db_result)) {
        $a_Tmp_Users[$d_row->userid] = $d_row;
    }
    
    return $a_Tmp_Users;
}

/**
 * User Information
 * @param array $a_users
 * @param array $a_course
 * @param connection $db_conn
 * @return array 
 */
function get_user_class($a_users, $a_course, $db_conn) {
    
    if ( !is_array($a_users) || empty($a_users)) { return array(); }
    
    $o_user_class         = new stdClass();
    $o_user_class->userid = '';
    $o_user_class->course = '';
    $o_user_class->team   = '';
    $o_user_class->level  = '';
    $o_user_class->crew   = '';

    // <editor-fold defaultstate="collapsed" desc="Default Value">
    $a_tmp_users = $a_users;

    foreach ($a_tmp_users as $key) {
        $a_tmp_users[$key] = array();
        if (empty($a_course)) {
            $a_tmp_users[$key]['0000'] = clone $o_user_class;
        }
        else {
            foreach ($a_course as $key1) {
                $a_tmp_users[$key][$key1] = clone $o_user_class;
            }
        }
    }
    // </editor-fold>
    $a_course        = array_filter($a_course);
    $v_tmp_condition = empty($a_course) ? "" : " and course in ('" . implode("', '", $a_course) . "')";
    
    $db_query = "
        select  ". implode(", ", array_keys((array)$o_user_class) ) ."
        from    user_class
        where   userid in ('" . implode("', '", $a_users ) . "') 
                $v_tmp_condition
        order by course";

    $db_result = db_query($db_conn, $db_query);

    while ($d_row = db_fetch($db_result)) {
        $a_tmp_users[$d_row->userid][$d_row->course] = $d_row;
    }
    
    return $a_tmp_users;
}

/**
 * Get Class to User
 * @param array $a_option
 * @param connection $db_conn
 * @return array 
 */
function get_class_to_user($a_option, $db_conn) {
    
    $a_default_option = array(
        'class_condition'=> '1=1',
        'user_condition' => '1=1',
    );
    
    $a_option = array_merge($a_default_option, $a_option);

    $a_users = $a_tmp_users = array();
    
    $db_query = "
        select  userid, team, level, crew, chuyencan, hocluc, rank, note
        from    user_class
        where   $a_option[class_condition]";

    $db_result = db_query($db_conn, $db_query);

    while ($d_row = db_fetch($db_result)) {
        $a_tmp_users[$d_row->userid] = $d_row;;
    }
    
    $db_query = "
        select  userid, usertype, saint, username
        from    user
        where   userid in ('" . implode("', '", array_keys($a_tmp_users) ) . "') and ($a_option[user_condition])";

    $db_result = db_query($db_conn, $db_query);

    while ($d_row = db_fetch($db_result)) {
        $a_tmp_users[$d_row->userid]->usertype = $d_row->usertype;
        $a_tmp_users[$d_row->userid]->saint    = $d_row->saint;
        $a_tmp_users[$d_row->userid]->username = $d_row->username;
        
        $a_users[$d_row->userid] = $a_tmp_users[$d_row->userid];
    }

    return $a_users;
}

/**
 * Hide Page
 * @param array $a_menu
 * @param array $a_page
 */
function hide_menu_from_page(&$a_menu, $a_page) {
    
    if (!is_array($a_menu) || empty($a_menu)) { return; }
    
    foreach ($a_menu as $key => $value) {
    
        if ($key == 'url' && in_array($value, $a_page)) { $a_menu = null; return; }
        
        if (is_array($value)) {
            hide_menu_from_page($a_menu[$key], $a_page);
            
            if (!$a_menu[$key] || (!isset($a_menu[$key]['submenu']) && @$a_menu[$key]['url'] == 'javascript:;')) {
                unset($a_menu[$key]);
            }
        }
    }
    
    return;
}

/**
 * Set Rank For Thieu-Nhi
 * @param array $a_option
 * @param connection $db_conn
 */
function set_user_rank($a_option, $a_KhoaHoc_Info, $a_Loai_ChuyenCan, $db_conn) {
    
    $a_default_option = array (
        'course'             => '',
        'team'               => '',
        'level'              => '',
        'crew'               => '',
        'user_condition'     => '1=1',
    );
    
    $v_course         = $a_option['course'];
    $v_team           = $a_option['team'];
    $v_level          = $a_option['level'];
    $v_crew           = $a_option['crew'];
    $v_user_condition = $a_option['user_condition'];

    $a_option = array_merge($a_default_option, $a_option);
    
    $a_average_hocluc = $a_average_chuyencan = $a_user = $a_rank = $a_tmp_rank = array ();
    
    // <editor-fold defaultstate="collapsed" desc="Get User ID">
    $db_query = "
        select  userid
        from    user_class
        where   team = '$v_team' and level = '$v_level' and crew = '$v_crew' and course = '$v_course' ";

    $db_result = db_query($db_conn, $db_query);

    while ($d_row = db_fetch($db_result)) {
        $a_user[$d_row->userid] = $d_row->userid;
    }
    // </editor-fold>
    
    if (!empty($a_user)) {

        /*
         * Only Update Rank For Thieu-Nhi
         */
        $db_query  = "
            select  userid
            from    user
            where   userid in ('" . implode("', '", $a_user) . "')" . " and $v_user_condition ";
        
        $db_result = db_query($db_conn, $db_query);
        unset($a_user);

        while ($d_row = db_fetch($db_result)) {
            $a_user            [$d_row->userid] = $d_row->userid;
            $a_average_chuyencan[$d_row->userid] = 10;
        }

        if (!empty($a_user)) {

            // <editor-fold defaultstate="collapsed" desc="Get Score">
            $v_startdate = date( $v_course + 0 . '-m-d', strtotime($a_KhoaHoc_Info['start']));
            $v_enddate   = date( $v_course + 1 . '-m-d', strtotime($a_KhoaHoc_Info['end'  ]));

            $db_query = "
                select  userid, scoretype, date, score, data
                from    user_score
                where   userid in ('" . implode("', '", $a_user) . "') and date >= '$v_startdate' and date <= '$v_enddate'
                order by date";

            $db_result = db_query($db_conn, $db_query);

            while ($d_row = db_fetch($db_result)) {

                if (in_array($d_row->scoretype, array_keys($a_Loai_ChuyenCan))) {
                    $a_average_chuyencan[$d_row->userid] += $d_row->data;
                } else {
                    $a_average_hocluc[$d_row->userid][$d_row->scoretype][$d_row->data] = $d_row->score;
                }
            }
            // </editor-fold>
        }

        // <editor-fold defaultstate="collapsed" desc="Set Rank">
        foreach ($a_user as $v_userid) {
            
            if (isset($a_average_hocluc[$v_userid])) {
                foreach ($a_average_hocluc[$v_userid] as $key => $value) {
                    $a_average_hocluc[$v_userid][$key] = array_sum($value) / count($value);
                }

                $a_average_hocluc[$v_userid] = array_sum($a_average_hocluc[$v_userid]) / count($a_average_hocluc[$v_userid]);
            }
            else {
                $a_average_hocluc[$v_userid] = 10;
            }
            
            if ($a_average_chuyencan[$v_userid] < 5 || $a_average_hocluc[$v_userid] < 5) {
                $a_rank[$v_userid] = 'O_LAI';
            }
            else if ($a_average_chuyencan[$v_userid] >= 9 && $a_average_hocluc[$v_userid] >= 8) {
                $a_rank    [$v_userid] = 'KHUYEN_KHICH';
                $a_tmp_rank[$v_userid] = $a_average_chuyencan[$v_userid] + $a_average_hocluc[$v_userid];
                
                if ($a_average_chuyencan[$v_userid] > $a_average_hocluc[$v_userid]) { $a_tmp_rank[$v_userid] += 0.000001; }
            }
            else {
                $a_rank[$v_userid] = 'LEN_LOP';
            }
        }
        
        asort($a_tmp_rank);
        
        $a_tmp_userid = array_keys($a_tmp_rank);

        if (!empty($a_tmp_userid)) { $v_userid = array_pop($a_tmp_userid); $a_rank[$v_userid] = 'HANG_I'  ; }
        if (!empty($a_tmp_userid)) { $v_userid = array_pop($a_tmp_userid); $a_rank[$v_userid] = 'HANG_II' ; }
        if (!empty($a_tmp_userid)) { $v_userid = array_pop($a_tmp_userid); $a_rank[$v_userid] = 'HANG_III'; }
        if (!empty($a_tmp_userid)) {
            
            foreach ($a_tmp_userid as $value) {
                if ($a_tmp_rank[$value] == $a_tmp_rank[$v_userid]) {
                    $a_rank[$value] = $a_rank[$v_userid];
                }
            }
        }
        // </editor-fold>
        
        foreach ($a_rank as $v_userid => $value) {
            
            $a_row = array(
                'chuyencan' => $a_average_chuyencan[$v_userid],
                'hocluc'   => $a_average_hocluc[$v_userid],
                'rank'     => $value,
                'note'     => '',
            );

            db_update_row($db_conn, $a_row, 'user_class', "userid = '$v_userid' and team = '$v_team' and level = '$v_level' and crew = '$v_crew' and course = '$v_course'");
        }
    }
}

/**
 * Build BreadCrumb and Set Active for Menu
 * @param type $a_menus
 * @param type $a_breadcrumb
 * @return boolean
 */
function set_breadcumb_active(&$a_menus, &$a_breadcrumb) {
    foreach ($a_menus as $key => $arr_menus) {
        if (is_array($a_menus[$key])) {
            
            if (isset($a_menus[$key]['submenu'])) {
                if (set_breadcumb_active($a_menus[$key]['submenu'], $a_breadcrumb) == true) {
                    $a_menus[$key]['active'] = true;
                    $a_breadcrumb[] = array('title'=> $a_menus[$key]['title'], 'url'=> $a_menus[$key]['url'] . '?' . @$a_menus[$key]['query']);
                    return true;
                }
            }
            else { 
                $v_tmp_scriptname = substr($_SERVER['SCRIPT_NAME'], strrpos($_SERVER['SCRIPT_NAME'], '/') + 1);
                if (@$a_menus[$key]['url'] == $v_tmp_scriptname || @in_array($v_tmp_scriptname, @$a_menus[$key]['modules'])) {
                    $a_menus[$key]['active'] = true;
                    $a_breadcrumb[]          = array ( 'title' => $a_menus[$key]['title'], 'url'   => $a_menus[$key]['url'] . '?' . @$a_menus[$key]['query'] );
                    return true;
                }
            }
        }
    }
}

/**
 * Generate BreadCrumb
 * @param array $a_breadcrumb
 */
function build_breadcumb_active($a_breadcrumb) {?>
    <ul class="breadcrumb">
        <li>
            <i class="icon-home"></i>
            <a href="index.php">Trang Chủ</a> 
    <?php if (!empty($a_breadcrumb) || !is_array($a_breadcrumb)) {
        for ($v_index = 0; $v_index < count($a_breadcrumb); $v_index++) { ?>
                <i class="icon-angle-right"></i>
            </li>
            <li>
                <a href="<?=$a_breadcrumb[$v_index]['url']?>"><?=$a_breadcrumb[$v_index]['title']?></a>
        <?php } 
    } ?>
            </li>
    </ul>
    <?php
}

/**
 * Generate Menu
 * @param array $a_menus
 */
function build_menu($a_menus) {
    foreach ($a_menus as $key => $arr_menus) {
        $v_tmp_class  = !$key? 'start' : '';
        $v_tmp_class  = @$arr_menus['active'] ? ' active' : '';
        $v_tmp_class .= @$arr_menus['class' ] ? $arr_menus['class'] : '';
        
        if (is_array($arr_menus)) { ?>
            <li class="<?=$v_tmp_class?>">
                <a href="<?= $arr_menus['url'] ?><?=@$arr_menus['query'] ? '?' . $arr_menus['query'] : ''?>" <?=@$arr_menus['target'] ? 'target="' . $arr_menus['target'] . '"' : ''?>>
                    <?php if (isset($arr_menus['icon'])) { ?>
                    <i class="icon-<?=$arr_menus['icon']?>"></i>
                    <?php } ?>
                    <span class="title"><?=$arr_menus['title']?></span>
                    <?php if (isset($arr_menus['submenu'])) { ?>
                    <span class="arrow"></span>
                    <?php } ?>
                </a>
                <?php if (isset($arr_menus['submenu'])) { ?>
                <ul class="sub-menu">
                    <?php build_menu($arr_menus['submenu']); ?>
                </ul>
                <?php } ?>
            </li>
            <?php
        }
    }
}

function generate_user_id($sUserType, $db_conn) {
    $sTempChar = $sUserType == 'HUYNH_TRUONG' ? 'HT' : date('y');
    $iNew_ID   = $sTempChar . '001';
    
    $db_query = "
            select  max(userid) as id
            from    user
            where   userid like '$sTempChar%'
            limit   1";
    
    $db_result = db_query($db_conn, $db_query);
    
    while ($oRow = db_fetch($db_result)) {
        $iNew_ID = substr($oRow->id, -3);
        $iNew_ID = (int)$iNew_ID + 1;
        $iNew_ID = strlen($iNew_ID) < 3 ? str_repeat(0, 3 - strlen($iNew_ID)) . $iNew_ID : $iNew_ID;
        $iNew_ID = $sTempChar . $iNew_ID;
    }

    return $iNew_ID;
}
?>